<?php
/**
 * IndexAction
 * blog的Action.接收和过滤网页传参
 * @uses Action
 * @package
 * @version $id$
 * @copyright 2009-2011 SamPeng
 * @author agui <aguihh@gmail.com>
 * @license PHP Version 5.2 
 */
 import("@.ORG.Page");
 require_once(SITE_PATH."/ThinkPHP/Common/extend.php");
class NoteAction extends Action {
    
    public function _initialize() 
    {
        $pid=Session::get('p_id');
    	if(empty($pid)){
          $this->redirect('Public/login');
        //  $this->error("请先登陆");  $pid
        }
	}
       public function index() {
              
              //$uid   = intval($_GET['$uid']);
             //   if($uid <= 0)
              //  	$this->error('参数错误');
                $uid=1;
              //  获得blog的列表
                $list  = $this->__getBlog($uid,'*','cTime desc');
                 
             //   归档数据
                $url = 'Index/index/uid/'.$uid;
              //    组装数据
                $list['url']=$url;
               // $name = 'agui';
               // $list['name']=$name;
                $this->assign('notelist', $list);
                $this->setTitle($name.'成长旅程');
                $this->display();
                
        }
          public function noteinfo()
          {
             $n_id=$_REQUEST['n_id'];
                if($n_id < 0){
                	$this->error('参数错误');
                 }
             $this->notedetail($n_id);
              
          }
  
         public function notedetail($n_id) {
             
                $note=new NoteModel();
                $note_info= $note->getNoteInfo($n_id);  
                 //   归档数据
                $url    = 'Index/noteinfo/nid/'.$n_id;
              //    组装数据
                
                $note_info['url']=$url;
                $note_info['ctime']=date('Y-m-d H:i',$note_info['ctime']);   
                $uid = $note_info['uid'];
                $note_info['p_name']=D('user')->where('u_id='.$uid)->find(); 
                 
                $condition['nid']=$n_id;
                $count=D('note_comment')->where($condition)->count();
                $p = new Page ($count,3);
                 //  获得blog的列表
               	$commnetList=D('note_comment')->where($condition)->limit($p->firstRow.','.$p->listRows)->findAll();
             
                $p->setConfig('header','条记录');
        		$p->setConfig('prev',"<");
        		$p->setConfig('next','>');
        		$p->setConfig('first','<<');
        		$p->setConfig('last','>>');
                $page = $p->show();
                
                foreach($commnetList AS $key=>$val){
                 $commnetList[$key]['ptime']=date('Y-m-d H:i',$val['ptime']);
                   
                }
                $this->assign('noteinfo', $note_info);
                $this->assign('page', $page);
               //global $ts; 
                $this->assign('commnetList',$commnetList);
                $this->setTitle($name.'成长旅程');
                $userid = Session::get('uid');
                if($note_info['uid'] == $userid){
                     $this->display("Tpl/default/Note/notedetail.html");
                }else{
                     $this->display("Tpl/default/Note/publicnotedetail.html");
                }
               
                
        }
      /**
       *日志评论 
       */
       public function addNoteComment(){
         $comments = $_POST['comment'];
         $noteId = $_POST['nid'];
         $Comm = D('note_comment');
         $data['content']= $comments;
         $data['p_name'] = Session::get('nick');
         $data['nid']= $noteId;
         $data['ptime']= time();
         $last = $Comm->add($data); 
         $condtion['id'] = $last;
         $List= $Comm->where($condtion)->find();
         $pTime = date("Y-m-d H:i:s",$List['ptime']);
         $this->ajaxReturn($List,$pTime,1,'json');  
    
    }
        /**
         * doDeleteblog
         * 删除blog
         * @access public
         * @return void
         */
        public function doDeleteblog() {

                $this->blog->id = $_REQUEST['id']; //要删除的id;
                $result         = $this->blog->doDeleteblog(null,$this->mid);

                if( false != $result) {					
					X('Credit')->setUserCredit($this->mid,'delete_blog');
                    redirect( U('blog/Index/my') );
                }else {
                    $this->error( "删除日志失败" );
                }
        }
        
          public function deletNote() {

               $nid = $_REQUEST['nid']; //要删除的id;
               if( $nid != 0) {					
				    $condtion['n_id'] = $nid;
                    $Last = M('Note')->where($condtion)->delete();
                    $condcomm['nid'] = $nid;
                    $Lastcomm = M('Note_comment')->where($condtion)->delete();
                    $this->notelist();
                }else {
                    $this->error( "删除日志失败" );
                }
        }

        
        /**
         * addBlog
         * 添加blog
         * @access public
         * @return void
         */
        public function addBlog() {
             $this->display();
        }
        /**
         * 编辑日志
         * @author sudi
         */
        public function editNote(){
         $nid = $_REQUEST['nid'];
         $condtion['n_id'] = $nid;
         $List= D('note')->where($condtion)->find();
         $this->assign('note',$List);
         $this->display("Tpl/default/Note/editnote.html");
        }
        
        public function doSaveBlog(){
            if(empty($_POST['title'])) {
            	$this->error( "请填写标题" );
            }
      		 if( mb_strlen($_POST['title'], 'UTF-8') > 25 ) {
					$this->error( "标题不得大于25个字符" );
             }
                   $content = $this->h($_POST['content']);
                //检查是否为空
             if( empty($_POST['content']) || empty( $content )  ) {
                 $this->error( "请填写内容" );
             }
                //得到发日志人的名字
              $username=Session::get('nick');
              $condtion['n_id'] = $_POST['nid'];
                //处理发日志的数据
                $data['title'] = $_REQUEST['title'];
                $data['content'] = $_REQUEST['content'];
                $data['ctime']=time();
                $data['uid']=Session::get('uid');
                $data['pid']=Session::get('p_id');
                //添加日志
                 $n_id=D('Note','home')->where($condtion)->save($data);
                 if($n_id>0){
                    $this->ajaxReturn($n_id,'保存成功！',1,'json');
                
                 }else {
                    $this->ajaxReturn(null,'保存失败！',0,'json');
                }
        }
        
        public function edit() {
                $id = $_GET['id'];
                if( $_GET['edit'] ) {
                        $outline = D( 'BlogOutline' );
                        //检查是否存在这篇日志
                        if( false == $list = $outline->getBlogContent( $id,null,$_GET['mid']))
                                $this->error( L( 'error_no_blog' ) );
                        //是否有权限修改本篇日志
                        //TODO 管理员
                        if( $list['p_id'] != $this->mid ) {
                                $this->error( L( 'error_no_role' ) );
                        }
              
                       //定义连接
                        $link = __URL__."&act=doAddBlog";
                       
                //编辑新的日志
                }else {
                        $link = __URL__."&act=doUpdate";
                        $dao = $this->blog;

                        if( false == $list = $this->blog->getBlogContent( $id,null,$_GET['mid'] ))
                                $this->error( L( 'error_no_blog' ) );

                        //是否有权限修改本篇日志
                        //TODO 管理员
                        if( $list['p_id'] != $this->mid )
                                $this->error( L( 'error_no_role' ) );
                }

                $this->assign( 'link',$link );
                $this->assign( $list );
                $this->display();
        }

        /**
         * doAddblog
         * 添加blog
         * @access public
         * @return void
         */
        public function doAddBlog() {
        	if(empty($_POST['title'])) {
            	$this->error( "请填写标题" );
            }
        		if( mb_strlen($_POST['title'], 'UTF-8') > 25 ) {
					$this->error( "标题不得大于25个字符" );
                }
                $content = $this->h($_POST['content']);
                //检查是否为空
                if( empty($_POST['content']) || empty( $content )  ) {
                        $this->error( "请填写内容" );
                }

                //得到发日志人的名字
              //  $userName = $this->blog->getOneName( $this->mid );
                 $username=Session::get('nick');
                //处理发日志的数据
                $data['title'] = $_REQUEST['title'];
                $data['content'] = $_REQUEST['content'];
                $data['ctime']=time();
                $data['uid']=Session::get('uid');
                $data['pid']=Session::get('p_id');
                //添加日志
               // $add = $this->blog->doAddBlog($data,true);
                 $n_id=D('Note','home')->add($data);
                  if($n_id>0){
                    $this->ajaxReturn($data,'添加成功！',1,'json');
                
                }else {
                     $this->ajaxReturn(null,'添加失败！',0,'json');
                }
        }

            public function notelist() {
        
                $uid=Session::get('uid');
              
                if($uid<0){
                   $this->error('参数错误！'); 
                }
                $contidion['uid']=$uid;
                $count=D('note')->where($contidion)->count();  
                $p = new Page ($count,5);
                 //  获得blog的列表
               	$list=D('note')->where($contidion)->limit($p->firstRow.','.$p->listRows)->order('n_id desc')->findAll();
             
                $p->setConfig('header','条记录');
        		$p->setConfig('prev',"<");
        		$p->setConfig('next','>');
        		$p->setConfig('first','<<');
        		$p->setConfig('last','>>');
                $page = $p->show();
                 foreach($list AS $key=>$val){
                    
                   $list[$key]['ctime']=date('Y-m-d H:i',$val['ctime']); 
                   $list[$key]['content'] =$this->cut_str($val['content'],35,0,'UTF-8');
             //      $contidion['p_id']=54;
             //      $p_name=D('parent')->where($contidion)->find();
                   $uid = $val['uid'];
                   $list[$key]['p_name']=D('user')->where('u_id='.$uid)->find();           
                 } 
                
                $this->assign('page', $page);
                $this->assign('notelist', $list);
                $this->setTitle($name.'成长旅程');
                $this->display("Tpl/default/Note/notelist.html");
                
        }

    /**
     *截取中文字符串 
     *Utf-8、gb2312都支持的汉字截取函数 
     *cut_str(字符串, 截取长度, 开始长度, 编码); 
     *编码默认为 utf-8 
     *开始长度默认为 0  
     */
    function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') 
      { 
            if($code == 'UTF-8') 
            { 
            $pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/"; 
            preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen)); 
            return join('', array_slice($t_string[0], $start, $sublen)); 
            } 
            else 
            { 
            $start = $start*2; 
            $sublen = $sublen*2; 
            $strlen = strlen($string); 
            $tmpstr = ''; for($i=0; $i<$strlen; $i++) 
            { 
            if($i>=$start && $i<($start+$sublen)) 
            { 
            if(ord(substr($string, $i, 1))>129) 
            { 
            $tmpstr.= substr($string, $i, 2); 
            } 
            else 
            { 
            $tmpstr.= substr($string, $i, 1); 
            } 
            } 
            if(ord(substr($string, $i, 1))>129) $i++; 
            } 
            if(strlen($tmpstr)<$strlen ) $tmpstr.= ""; 
            return $tmpstr; 
            } 
        } 

        /**
         * doUpdate
         * 执行更新日志动作
         * @access public
         * @return void
         */
        public function doUpdate() {
        		if (empty($_POST['title'])) {
                    $this->error( "请填写标题" );
                }
        		if (mb_strlen($_POST['title'], 'UTF-8') > 25 ) {
                	$this->error( "标题不能大于25个字符" );
                }
                $content = h($_POST['content']);
				
                if( empty( $content ) ) {
                    $this->error( "请填写内容" );
                }

                $userName = $this->blog->getOneName( $this->mid );

                $id       = intval($_POST['id']);
                //检查更新合法化
                if( $this->blog->where( 'id = '.$id )->getField( 'uid' ) != $this->mid ) {
                        $this->error( L('error_no_role') );
                }
                $data = $this->__getPost();
                $save = $this->blog->doSaveBlog($data,$id);

                if ($save) {
                    redirect(U('blog/Index/show', array('id'=>$id, 'mid'=>$this->mid)));
                } else {
                    $this->error( "修改失败" );
                }
        }
       /**
         * autoSave
         * 自动保存
         * @access public
         * @return void
         */
        public function autoSave(  ) {
                $content = trim(str_replace('&amp;nbsp;','',t($_POST['content'])));
                //检查是否为空
                if( empty($_POST['content']) || empty( $content )  ) {
                        $this->error( "请填写内容" );
                        exit();
                }
                $add="";
                $userName = $this->blog->getOneName( $this->mid );
                //处理数据
                $data['name']     = $userName['name'];
                $data['content']  = $_POST['content'];
                $data['pid']      = $this->mid;
                $data['password'] = $_POST['password'];
                $data['title']    = !empty($_POST['title']) ?$_POST['title']:"无标题";
                $data['canableComment'] = intval(t($_POST['cc']));
                if( isset( $_POST['updata'] ) ) {
                //更新数据，而不是添加新的草稿
                        $add = intval(trim($_POST['updata']));
                        $result = $this->blog->updateAuto( $data,$add );
                }else {
                //自动保存
                        $add = $this->blog->autoSave($data);
                }
                if( $add || $result) {
                        echo date('Y-m-d H:i:s',time()).",".$add;
                }else {
                        echo -1;
                }
        }

        /**
         * outline
         * 草稿箱
         * @access public
         * @return void
         */
        public function outline(  ) {
                $this->assign( $list );
                $this->display();
        }

        /**
         * deleteOutline
         * 删除
         * @access public
         * @return void
         */
        public function deleteOutline(  ) {
                if( empty($_POST['id']) ) {
                        echo -1;
                        return;
                }
                $map['id'] = array( "in",array_filter( explode( ',' , $_POST['id'] ) ));
                $outline = D( 'BlogOutline' );
                //检查合法性
                if( $outline->where( $map )->getField( 'uid' ) != $this->mid ) {
                        echo -1;
                }

                if( $result = $outline->where( $map )->delete() ) {
                        echo 1;
                }else {
                        echo -1;
                }
        }   
        /**
         * TODO 删除
         */
        public function commentSuccess() {
        //$post = str_replace('\\', '', stripslashes($_POST['data']));
                $result = json_decode(stripslashes($_POST['data']));  //json被反解析成了stdClass类型
                $count = $this->__setBlogCount($result->appid);

                //发送两条消息
                $data = $this->__getNotifyData($result);
                $this->api->comment_notify('blog',$data,$this->appId);
                echo $count;
        }
        /**
         * TODO 删除
         */
        public function deleteSuccess() {
                $id = $_POST['id'];
                echo $this->__setBlogCount($id);;
        }
        /**
         * TODO 删除
         */
        private function __setBlogCount($id) {
                $count = $this->api->comment_getCount('blog',$id);
                $result = $this->blog->setCount($id,$count);
                return $count;
        }        
        /**
         * __getblog
         * 获得blog列表
         * @param int|array|string $uid uid
         * @access private
         * @return void
         */
        private function __getBlog ($uid=null,$field=null,$order=null,$limit=null) {
        	//将数字或者数字型字符串转换成整型
                is_numeric( $uid ) && $uid = intval( $uid );

                //给blog对象的uid属性赋值
                if( isset( $uid ) ) {
                        $map['p_id']   = $uid;
                }
                 $note=new NoteModel();
                 
               return  $note->getNoteList ($map, $field, $order);
}
        /**
         * _getWiget
         * 获得需要传递给widget的数据
         * @param mixed $link
         * @param mixed $uid
         * @access private
         * @return void
         */
        private function _getWiget($link,$uid) {
                $condition['uid'] = $uid;
                if( empty( $uid) )
                        unset( $condition);
                $map['fileaway']  = L( 'fileaway' );
                $map['link']      = $link;
                $map['condition'] = $condition ;
               // $map['limit']     = D('Note')->getConfig( 'fileawaypage' );
                $map['tableName'] = C('DB_PREFIX').'_blog';
                $map['APP']       = __APP__;
                return $map;
        }

        /**
         * _paramUrl
         * 解析导入的路径
         * @param mixed $url
         * @access private
         * @return void
         */
        private function _paramUrl( $url ) {
        //判断合法性
                if ( false == preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $url)) {
                        $this->error( "不是合法的URL格式" );
                        return false;
                }
                $result = array( 'service'=>'','username'=>'' );
                $url      = str_replace( 'http://','',$url );
                $urlarray = explode( '/',$url );
                $target   = array( '163','baidu','spaces','sohu','sina','msn' );
                foreach( $target as $value ) {
                        if( strpos( $urlarray[0],$value ) ) {
                                switch( $value ) {
                                        case '163':
                                                $result['service'] = '163';
                                                $temp = explode( '.',$urlarray[0] );
                                                $result['username'] = $temp[0];
                                                break;
                                        case 'baidu':
                                                $result['service'] = 'baidu';
                                                $result['username'] = $urlarray[1];
                                                break;
                                        case 'sohu':
                                                $result['service'] = 'sohu';
                                                $temp = explode( '.',$urlarray[0] );
                                                $result['username'] = $temp[0];
                                                break;
                                        case 'sina':
                                                $result['service'] = 'sina';
                                                $result['username'] = isset( $urlarray[2] )?$urlarray[2]:$urlarray[1];
                                                break;
                                        case 'msn':
                                                $result['service'] = 'msn';
                                                $result['username'] = $urlarray[1];
                                                break;
                                        case 'spaces':
                                                $result['service'] = 'msn';
                                                $temp = explode( '.',$urlarray[0] );
                                                $result['username'] = $temp[0];
                                                break;
                                        default:
                                                $this->assign( '错误的URL' );
                                                return false;
                                //throw new ThinkException( "错误的url" );
                                }
                        }
                }
                //检测格式。过滤掉特殊格式。防止解析出错
                if( strpos( '.', $result['username'] ) ) {
                        return false;
                }elseif( strpos( '/',$result['username'] ) ) {
                        return false;
                }
                return $result;
        }

        /**
         * _getImportData
         * 获得引入日志的数据
         * @param mixed $result
         * @access private
         * @return void
         */
        private function _getImportData( $result ) {
                if( !empty( $result['change_ids'] ) ) {
                        $map = "`id` IN ( ".implode( ",",$result['change_ids'] )." )";
                }

                if( !empty( $result['change_ids'] ) && !empty( $result['source_id'] ) ) {
                        $map .= " OR ";
                }

                if( !empty( $result['source_id'] ) ) {
                        $map .= '(`sourceId` = '.$result['source_id']." AND `boot` = 0)";
                }

                $item = D( 'BlogItem' );
                $importBlog = $item->getItem( $map,'id,link,title' );
                return $importBlog;
        }
             
        private function _checkUser( $uid ) {
                $result = $this->api->user_getInfo($uid,'id');
                return $result;
        }
        
    //输出安全的html
public function h($text, $tags = null){
	$text	=	trim($text);
	//完全过滤注释
	$text	=	preg_replace('/<!--?.*-->/','',$text);
	//完全过滤动态代码
	$text	=	preg_replace('/<\?|\?'.'>/','',$text);
	//完全过滤js
	$text	=	preg_replace('/<script?.*\/script>/','',$text);

	$text	=	str_replace('[','&#091;',$text);
	$text	=	str_replace(']','&#093;',$text);
	$text	=	str_replace('|','&#124;',$text);
	//过滤换行符
	$text	=	preg_replace('/\r?\n/','',$text);
	//br
	$text	=	preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
	$text	=	preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
	//过滤危险的属性，如：过滤on事件lang js
	while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1],$text);
	}
	while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].$mat[3],$text);
	}
	if(empty($tags)) {
		$tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
	}
	//允许的HTML标签
	$text	=	preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text);
	//过滤多余html
	$text	=	preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i','',$text);
	//过滤合法的html标签
	while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
	}
	//转换引号
	while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
	}
	//过滤错误的单个引号
	while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
	}
	//转换其它所有不合法的 < >
	$text	=	str_replace('<','&lt;',$text);
	$text	=	str_replace('>','&gt;',$text);
	$text	=	str_replace('"','&quot;',$text);
	 //反转换
	$text	=	str_replace('[','<',$text);
	$text	=	str_replace(']','>',$text);
	$text	=	str_replace('|','"',$text);
	//过滤多余空格
	$text	=	str_replace('  ',' ',$text);
	return $text;
}    
}